package cn.liutao.auth.api;

import cn.hutool.core.util.StrUtil;
import cn.liutao.auth.entity.po.User;
import cn.liutao.auth.service.UserService;
import cn.liutao.common.entity.Validation;
import cn.liutao.common.enums.CommonEnum;
import cn.liutao.common.utils.AuthUtils;
import cn.liutao.common.utils.ServletUtils;
import cn.liutao.common.utils.ValidUtil;
import com.mybatisflex.core.paginate.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liutao
 * @Description 用户信息管理
 * @date 2023/11/1 8:27
 * @Version 1.0
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() {
        userService = UserService.getInstance();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        AuthUtils.isAdmin();
        User queryParam = ServletUtils.getQueryParam(req, User.class);
        Page<User> userPage =  userService.selectList(queryParam);
        List<User> userList = userPage.getRecords().stream().map(user -> {
            if (StrUtil.isBlank(user.getAvatar())) user.setAvatar(CommonEnum.DEFAULT_AVATAR_IMAGE.getValue());
            return user;
        }).collect(Collectors.toList());
        userPage.setRecords(userList);
        ServletUtils.ok(resp,userPage);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        AuthUtils.isAdmin();
        User addParam = ServletUtils.getBodyParam(req, User.class);
        ValidUtil.validated(addParam,Validation.AddGroup.class);
        userService.insert(addParam);
        ServletUtils.ok(resp,"添加成功");
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User editParam = ServletUtils.getBodyParam(req, User.class);
        ValidUtil.validated(editParam,Validation.EditGroup.class);
        userService.updateById(editParam);
        ServletUtils.ok(resp,"修改成功");
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        AuthUtils.isAdmin();
        List<String> ids = ServletUtils.getQueryParams(req, "id");
        for (String id : ids) {
            userService.removeById(Integer.valueOf(id));
        }
        ServletUtils.ok(resp,"删除成功");
    }
}
